package com.haifeng.asms.auth.config;

import cn.hutool.core.util.ArrayUtil;
import com.haifeng.asms.auth.handler.LogOutSuccessHandler;
import com.haifeng.asms.auth.handler.LoginEntryPoint;
import com.haifeng.asms.auth.handler.LoginFailureHandler;
import com.haifeng.asms.auth.handler.LoginSuccessHandler;
import com.haifeng.asms.auth.properties.SecurityProperties;
import lombok.AllArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Set;

/**
 * <p>
 *  Web安全配置
 * </p>
 *
 * @author: Haifeng
 * @date: 2020-06-22
 */
@Order(2)
@Configuration
@AllArgsConstructor
@EnableConfigurationProperties(SecurityProperties.class)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final LoginSuccessHandler loginSuccessHandler;
    private final LoginFailureHandler loginFailureHandler;
    private final LogOutSuccessHandler logOutSuccessHandler;
    private final SecurityProperties securityProperties;

    /**
     * 配置加密方式BCryptPasswordEncoder
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    @Bean("authenticationManagerBean")
    public AuthenticationManager authenticationManagerBean() throws Exception{
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        Set<String> noLoginUrls = securityProperties.getNoLoginUrls();
        http.formLogin()
                .loginProcessingUrl(securityProperties.getLoginUrl())
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler)
            .and()
            .logout()
                .logoutUrl(securityProperties.getLogoutUrl())
                .logoutSuccessHandler(logOutSuccessHandler)
                .deleteCookies(securityProperties.getCookies())
            .and()
                .exceptionHandling().authenticationEntryPoint(new LoginEntryPoint())
            .and()
                .authorizeRequests()
                .antMatchers(ArrayUtil.toArray(noLoginUrls.iterator(),String.class)).permitAll()
                .anyRequest().authenticated()
                .and()
                .csrf().disable();
    }
}
